<template>
	<view class="tui-center">
		<uni-nav-bar fixed left-icon="back" title="确认订单" @clickLeft="clickLeft()"></uni-nav-bar>
		<view style="margin: 20rpx;color: #999;">
			<view>提示：周票、月票、季票、年票使用日期选择出行日期，结束日期自动补充。</view>
		</view>
		<view class="tui-book-box">
			<uni-forms :value="addressData" ref="form" :rules="rules" err-show-type="undertext" labelWidth="180">
				<uni-forms-item required label="出行日期:" name="businName">
					<view class="tui-flex" @tap="openDate">
						<view v-if="addressData.useStartDate == ''"
							  style="flex: 1;font-size: 34rpx;color: grey;padding-left: 20rpx">
							请选择
						</view>
						<view v-else style="flex: 1;font-size: 32rpx" >
							{{addressData.useStartDate}}
							<text v-if="endDate" style="padding: 0 10rpx"> ~ </text>
							{{endDate}}
						</view>
						<uni-icons type="arrowdown" color="#999" size="30"></uni-icons>
					</view>
				</uni-forms-item>
				<uni-forms-item label="留言:" name="buyerMessage">
					<uni-easyinput :inputBorder="false" v-model="addressData.buyerMessage" type="text" placeholder="请填写留言" />
				</uni-forms-item>
				<uni-forms-item label="联系人:">
					<view @tap="coolseTo" style="text-align: right;color: #999;">
						<text>选择联系人</text>
						<uni-icons type="arrowright" color="#999" size="40"></uni-icons>
					</view>
				</uni-forms-item>
			</uni-forms>
		</view>

		<view class="tui-book-box" v-if="contactShow">
			<view style="color: #999;">
				已选联系人:
			</view>
			<view style="padding: 10rpx 0">
				<view class="l_item" v-for="(item, index) in contactList" :key="index">
					<view>{{item.userName}}</view>
					<view style="padding-left: 30rpx;">{{item.cardNo}}</view>
				</view>
			</view>
		</view>

		<view class="tui-book-box">
			<view class="tui-flex" style="background: #f8f8f8;padding: 6rpx 15rpx;">
				<view class="image">
					<image class="det-img" :src="list.url" alt="" mode="aspectFill"/>
				</view>
				<view class="tui-book-name">
					<view class="title">{{list.title}}</view>
					<view style="color: #999;">{{skuList.name}}</view>
					<view style="display: flex;justify-content: space-between;align-items: center;">
						<view>数量: x{{addressData.num}}</view>
						<view>￥{{skuList.discoutPrice ? skuList.discoutPrice : skuList.price}}</view>
					</view>
				</view>
			</view>
			<!--<view class="tui-flex ui-dashed">
				<view class="flex-num">购买数量:</view>
				<view class="num-box">
					<number-box :value="addressData.num"
								:min="0"
								:disabled="true"
								:step="1"
								@change="daysChange">
					</number-box>
				</view>
			</view>-->
			<view class="tui-flex ui-dashed" style="padding-top: 20rpx; ">
				<view class="flex-num">商品总金额:</view>
				<view class="txt">￥<text class="price">{{totalNumMoney}}</text></view>
			</view>

		</view>

		<view class="tui-book-box">
			<view class="tui-flex ui-dashed" @tap="showModal = !showModal">
				<view class="flex-num">优惠券:</view>
				<view :style="{color:couponText != '暂无优惠券'?'#FF6666':'#999'}">{{couponText}}</view>
				<view><uni-icons type="arrowright" size="36" color="#999"></uni-icons></view>
			</view>
			<view class="tui-flex ui-dashed">
				<view class="tit">
					余额(<text style="font-size: 28rpx;color: #FF6666">
					￥{{walletBalance||0}}
					</text>)
				</view>
				<view class="ipt uni-easyinput">
					<text style="color: #FF6666">-￥{{Balance}}</text>
				</view>
			</view>
			<view class="num-bot">
				<view>小计：<text style="color: #FF6666;">￥{{totalMoney}}</text></view>
			</view>
		</view>

		<good-date-picker ref="goodDatePicker" @change="changeDate" :option="goodDatePickerOption" @clickDay="clickDay"/>
		<good-date-picker ref="dayDatePicker" @change="dayDate" :option="goodDayPickerOption"/>

		<!--按钮-->
		<pay-btn :amount="totalMoney" title="总计" payText="提交订单" @imPayment="imPayment(list)"></pay-btn>
        <list-popup isMore :isShow="isShow" :list="popList" @pushdic="pushdic"
					@closepop="isShow = true" @closeShow="isShow=false"/>

		<coupon-modal :isShow="showModal"
					  :list="listData"
					  :businId="list.businId"
					  :money="totalNumMoney"
					  @closeAlert="handeClose"
					  @closeBtnClose="showModal = !showModal"
					  @nonuseClick="nonuseClick"
		></coupon-modal>

		<!-- 登录提示 -->
		<uni-login-model></uni-login-model>
	</view>
</template>

<script>
	import GoodDatePicker from '@/components/good-date-picker/good-date-picker.vue'
    import payBtn from '@/components/payBtn/index'
    import uniIcons from '@/components/uni-icons/uni-icons.vue'
    import uniForms from '@/components/bjx-form/uni-forms.vue'
    import uniFormsItem from '@/components/bjx-form/uni-forms-item.vue'
    import uniEasyinput from '@/components/bjx-form/uni-easyinput.vue'
    import numberBox from '@/components/uni-number-box/number-box.vue'
    import couponModal from '@/components/coolc-coupon/coupon-modal.vue'
    import listPopup from './listPopup'
    import uniLoginModel from '@/components/uni-login-model/uni-login-model.vue'
    import { mapState } from 'vuex'
	
	export default {
		name: 'bookTicket',
		components: {
			GoodDatePicker, payBtn, uniIcons, uniForms, couponModal,
			uniFormsItem, uniEasyinput, numberBox, listPopup, uniLoginModel
		},
		data() {
			return {
				name: '',
				pric: '',
				index: 0,
                endDate: '',
                showModal: false,
                addressData: {
                    phone: '',
                    useStartDate: '',
                    useEndDate: '',
                    num: 1,
				},
				editForm: {
                    cartProductDtoList: [
						{
                            businId: 0,
                            orderId: '',
                            orderSpec: '',
                            ownSpec: '',
                            pics: '',
                            price: '',
                            productName: '',
                            productNo: '',
                            skuId: '',
                            title: ''
						}
					],
                    ownSpec: '',
                    phone: '',
                    productType: '',
                    totalAmount: '',
                    actAmount: '',
				},
                rules: {
                },
				list: {
                    businId: null,
                    createTime: null,
                    isHot: null,
                    name: null,
                    price: null,
                    sort: null,
                    title: null,
                    type: null,
                    spuId: null,
                    url: null,
                    isTicket: null,
                    productId: null
				},
				checked: true,
				checkNum: '5.00',
				goodDatePickerOption: {
					chooseOneDate: "", //根据实际业务需求设置的默认单选日期，可为空,默认今天
					initStartDate: '', //可选起始时间限制，可为空,默认今天
					initEndDate: '', //可选结束时间限制，可为空,默认4个月后
					isRange: true, //是否开启范围选择，必填
					isModal:true,//是否弹窗模式，默认false
					isShowSubmit:false,//页面模式中是否显示页面模式底部的确定按钮，默认false
                    startText: '开始',
                    endText: '结束'
				},
                goodDayPickerOption: {
                    chooseOneDate: "", //根据实际业务需求设置的默认单选日期，可为空,默认今天
                    initStartDate: '', //可选起始时间限制，可为空,默认今天
                    initEndDate: '', //可选结束时间限制，可为空,默认4个月后
                    isRange: false, //是否开启范围选择，必填
                    isModal:true,//是否弹窗模式，默认false
                    isShowSubmit:false,//页面模式中是否显示页面模式底部的确定按钮，默认false
				},
				codeUrl: null,
                totalMoney: 0,
                skuList: {
                    ownSpec: {monthlyTicket: ''}
				},
                popList: [],
                isShow: false,
                contactList: [{
                    useStartDate: '', useEndDate: ''
				}],
                contactShow: false,
                walletBalance: 0,
                Balance: 0,
                listData: [],
                couponText: '暂无优惠券',
                couponData: {},
                totalNumMoney: 0
			}
		},
        computed: {
            ...mapState({
                userInfo: state => state.user.userInfo
            })
        },
		onLoad(option) {
            this.walletBalance = this.userInfo.walletBalance
		    this.skuList = JSON.parse(option.data)
			this.addressData.num = this.skuList.count
            if (this.skuList.ownSpec) {
                this.skuList.ownSpec = JSON.parse(this.skuList.ownSpec)
			}
            this.getList(option.id)
            this.getPopList()
        },
		methods: {
            getList(id) {
                uni.showLoading()
                uni.request({
                    url: `good/detail/${id}`,
                    method: 'GET',
                    header: {
                        'content-type': 'application/json',
                        'Authorization': 'Bearer ' + uni.getStorageSync('token')
                    }, success: (res) => {
                        uni.hideLoading();
                        if (res.data.code == 200) {
                            this.list = res.data.data
                            this.totalNumMoney = this.skuList.discoutPrice ? this.skuList.discoutPrice : this.skuList.price
                            this.totalMoney = this.skuList.discoutPrice ? this.skuList.discoutPrice : this.skuList.price
                            this.loadData()
                            this.calcTotal()
                            let num = 0
                            if (this.walletBalance>this.totalNumMoney) {
                                let balance  = this.walletBalance - (this.walletBalance - this.totalNumMoney)
                                this.Balance = Number(balance.toFixed(2))
                            } else {
                                num  = this.totalNumMoney - this.walletBalance
                                this.Balance = this.walletBalance
                            }
                            this.totalMoney = Number(num.toFixed(2))
                            if (this.totalMoney <=0) {this.totalMoney = 0}
						}
					}, fail: (res) => {
                        uni.hideLoading();
                        this.$api.msg(res.data.message)
                    }
                })
            },
			//	提交订单
            imPayment(item) {
                console.log(this.skuList)
                this.editForm.cartProductDtoList.forEach(i => {
                    this.$set(i,'title',this.skuList.name)
                    this.$set(i,'productName',this.skuList.name)
                    this.$set(i,'pics',this.skuList.img)
                    this.$set(i,'pic',this.skuList.img)
                    this.$set(i,'num',this.addressData.num)
                    this.$set(i,'businId',this.list.businId)
					this.$set(i, 'productNo',this.skuList.skuCode)
                    this.$set(i, 'price',this.skuList.price)
                    this.$set(i, 'skuId',this.skuList.skuId)
                    this.$set(i, 'stock',this.skuList.stock)
                    return
                })
				let data = this.addressData
				if(!data.useStartDate){
					uni.showModal({ content: '请选择出行日期', showCancel: false });
					return;
				}
                this.contactList.forEach(item => {
                    this.$set(item, 'useStartDate',data.useStartDate)
					this.$set(item, 'useEndDate', data.useEndDate)
                    // return
				})
                // !this.contactList.length
				if (this.skuList.ownSpec.monthlyTicket == '年票' && !this.contactList.length) {
                    uni.showModal({ content: '请选择联系人', showCancel: false });
                    return;
				}
                /*if (this.addressData.num > this.contactList.length || this.contactList.length > this.addressData.num ) {
                    this.$api.msg('数量与旅客信息不不符！')
                    return
                }*/
                console.log('contactList',this.contactList)
                this.editForm = {
                    ...this.editForm,
                    productType: this.list.type,
                    couponId: this.couponData.couponId,
                    shopId: this.list.businId,
                    balance: this.Balance,
                    totalAmount: this.totalNumMoney,
                    actAmount: this.totalMoney,
                    couponAmount: this.couponData.faceValue,
                    // ownSpec: JSON.stringify(this.addressData)
                    ownSpec: JSON.stringify(this.contactList)
                }
                uni.showLoading()

				/**2021/12/9 15:19 tan_yi 校验优惠券和商户是否匹配*/
				// 获取优惠券ID、优惠券对应的门店id1
				console.log("优惠券改动")
				console.log(this.listData)

				// 获取使用门店的id2

				// id1 <> id2 校验失败


				/**2021/12/9 15:19 tan_yi*/

				this.$api.api('order.create', this.editForm).then(res => {
					if (res.code == 200) {
                        uni.hideLoading();
                        this.$wx.miniProgram.reLaunch({
                            url: `/pages/ticketPay/ticketPay?money=${this.totalMoney}&orderNo=${res.data.orderNo}&orderId=${item.spuId}&productType=0`,
                            success: function(){},
                            fail: function(err){},
                            complete:function(){}
                        });
					} else {
                        uni.hideLoading();
                        this.$api.msg(res.message)
					}
				}).catch(error => { this.$api.msg(error.message) })
			},
            nonuseClick(e) {

			},
            handeClose(data) {
                this.showModal = false
                this.couponData = data
				if (data.faceValue == 0) {
                    this.couponText = data.name
				} else {
                    this.couponText = '-￥'+data.faceValue
				}
                let num = 0
				if (data.faceValue>=this.totalNumMoney) {
                    this.Balance = 0
                    let number1 = data.faceValue - this.totalNumMoney
                    this.totalMoney = Number(number1.toFixed(2))
				} else if (this.walletBalance>=this.totalNumMoney) {
                    let money = this.walletBalance -(this.walletBalance - this.totalNumMoney) - data.faceValue
                    num = Number(money.toFixed(2))
                    this.Balance = num
                } else {
                    this.Balance = this.walletBalance
                    num  = this.totalNumMoney - this.Balance - data.faceValue
                    this.totalMoney = Number(num.toFixed(2))
                }
                if (this.totalMoney <= 0) { this.totalMoney = 0 }
            },
            //	获取优惠券列表
            loadData() {
				console.log("获取优惠券列表");
                uni.showLoading()
				//	, {status: 0}
                this.$api.api('coupon.list', {status: 0}).then(res => {
					
                    uni.hideLoading();
                    if (res.code == 200 ){
						this.listData = res.data;
                        for (var i = 0, lenI = this.listData.length; i < lenI; ++i) {
                            this.listData[i].couponId = String(this.listData[i].couponId)
                        }
                        let list = [],matched;
						
						// 判断优惠券是否满足要求
						let flag = false;
						
						/* tanyi update 2021-12-10*/
						for (let i in res.data) {
							console.log("第", +i, "次，优惠券所属门店 = ", +res.data[i].bindShopIds, "当前门店," +this.list.businId)
							// 1. 优惠券所属门店 == 当前门店
							if (res.data[i].bindShopIds != this.list.businId) {
								console.log("门店不匹配")
								continue;
							}
							
							// 2. 优惠券金额 < 当前交易金额
							if (res.data[i].useConditionType == 'FULL_REDUCTION' && res.data[i].useConditionValue < this.totalNumMoney) {
								console.log("优惠券金额>当前订单金额")
								continue;
							}
							
							list.push(res.data[i])
							this.couponText = `有${list.length}张可用`
							this.listData = list
							flag = true;
							
						}
						
						if (!flag) {
							this.listData = [];
						}
						
                        /* res.data.forEach((item, index) => {
                            // matched = item.bindShopIds.find((value)=>{return value == this.list.businId})
							
							console.log("第", +index, "次，优惠券所属门店 = ", +item.bindShopIds, "当前门店," +this.list.businId)
							// 1. 优惠券所属门店 == 当前门店
							if (item.bindShopIds != this.list.businId) {
								console.log("门店不匹配")
								continue;
							}
						
                            if ((item.useConditionType == 'NONE' && matched) || 
							(item.useConditionType == 'FULL_REDUCTION' && item.useConditionValue < this.totalNumMoney && matched) || 
							this.totalNumMoney < item.faceValue){
                                list.push(item)
                                this.couponText = `有${list.length}张可用`
                                this.listData = list
								
                            } else {
                                this.listData = []
                            } 
                        }) */
						
					
                    } else {
                        uni.showToast({title: res.message, icon: 'none'})
                    }
                }).catch(error => {
                })
            },
            formatTime(d) {
                var year = d.getFullYear();
                var month = d.getMonth() + 1;
                var date = d.getDate();
                var hour = d.getHours();
                var minute = d.getMinutes();
                var second = d.getSeconds();
                return year + "-" + (Date[month] || month) + "-" + (Date[date] || date)
            },
            //数量
            daysChange(e) {
                this.addressData.num = e
                this.calcTotal()
            },
			//	起始日期
            changeDate(e) { //单选择完日期回调，
                this.addressData.useStartDate=e.startDate;//单选模式下返回当前选择的日期
                this.addressData.useEndDate = e.endDate;
            },
            clickDay(e) {
				let day;
				if (this.skuList.ownSpec.monthlyTicket == '月票') {
					this.addressData.useStartDate = e
                    this.addressData.useEndDate = this.getBeforeDate(30, e)
                    this.$refs.goodDatePicker.close();
				}
			},
            getBeforeDate(num, time) {
                let n = num;
                let d = '';
                if(time) { d = new Date(time);
                } else { d = new Date(); }
                let year = d.getFullYear();
                let mon = d.getMonth() + 1;
                let day = d.getDate();
                if(day <= n) {
                    if(mon > 1) { mon = mon - 1;
                    } else {
                        year = year - 1;
                        mon = 12;
                    }
                }
                d.setDate(d.getDate() - n);
                year = d.getFullYear();
                mon = d.getMonth() + 1;
                day = d.getDate();
                let s = year + "-" + (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
                return s;
            },
			//	单日期
            dayDate(e) {
				let day = e.currentDate
                this.$refs.goodDatePicker.close();
                if (this.skuList.ownSpec.monthlyTicket == '月票') {
                    this.addressData.useStartDate = day
                    this.addressData.useEndDate = this.getBeforeDate(-30, day)
					this.endDate = this.getBeforeDate(-30, day)
                } else if (this.skuList.ownSpec.monthlyTicket == '日票') {
                    this.addressData.useStartDate = day
                    this.addressData.useEndDate = day + ' 23:59:59'
				} else if (this.skuList.ownSpec.monthlyTicket == '周票') {
                    this.addressData.useStartDate = day
                    this.addressData.useEndDate = this.getBeforeDate(-7, day)
                    this.endDate = this.getBeforeDate(-7, day)
				} else if (this.skuList.ownSpec.monthlyTicket == '年票') {
                    this.addressData.useStartDate = day
                    this.addressData.useEndDate = this.getBeforeDate(-365, day)
                    this.endDate = this.getBeforeDate(-365, day)
				} else if (this.skuList.ownSpec.monthlyTicket == '季票') {
                    this.addressData.useStartDate = day
                    this.addressData.useEndDate = this.getBeforeDate(-90, day)
                    this.endDate = this.getBeforeDate(-90, day)
				} else if (this.skuList.ownSpec.monthlyTicket == '国庆票') {
                    this.addressData.useStartDate = day
                    this.addressData.useEndDate = '2021-10-07 23:59:59'
                    this.endDate = '2021-10-07 23:59:59'
                }
                console.log(this.skuList.ownSpec.monthlyTicket)
			},
            openDate() { //打开日期弹窗
                /*console.log(this.skuList.ownSpec.monthlyTicket)
                if (this.skuList.ownSpec.monthlyTicket == '日票') {
                    this.$refs.dayDatePicker.open()
                } else {
                    this.$refs.goodDatePicker.open();
                }*/
                this.$refs.dayDatePicker.open()
            },
            calcTotal() {
                let total = 0;
                let price = this.skuList.discoutPrice ? this.skuList.discoutPrice : this.skuList.price
                total += price * this.addressData.num
				/*if (this.couponData.faceValue) {
                    total = total - this.couponData.faceValue
				}*/
				console.log('total',+total)
                this.totalMoney = Number(total.toFixed(2));
                this.totalNumMoney = Number(total.toFixed(2));
            },
            clickLeft() {
                uni.navigateBack()
            },
			coolseTo() {
                this.selidx = this.contactList
                this.isShow = true
			},
            getPopList() {
                this.$api.api('contact.list').then(res => {
                    this.popList = res.data.list
                }).catch(error => {
                    this.popList = []
                });
            },
            pushdic(e) {
                console.log(e == '[]')
				this.contactList = JSON.parse(e)
				if (e != '[]') {
                    this.contactShow = true
				} else {
                    console.log(e)
                    this.contactShow = false
				}
				this.isShow = false
			}
		}
	}
</script>

<style lang="scss">
	.tui-center {
		padding-bottom: 130rpx;
	}
	.tui-book-box {
		margin: 20rpx;
		background-color: #fff;
		padding: 30rpx;
		border-radius: 16rpx;
		.tui-flex {
			padding: 15rpx 0;
			/*border-bottom: 2rpx solid #eee;*/
			&:last-child{
				border-bottom: 0;
			}
		}
		.tui-farepay-txt {
			color: red;
		}
		.radio {
			/deep/ .uni-radio-input{
				width: 40rpx;
				height: 40rpx;
			}
			/deep/ .uni-radio-input-checked {
				&:before {
					font-size: 36rpx;
				}
			}
		}
	}
	.image {
		width: 30%;
		padding-right: 20rpx;
		height: 140rpx;
		.det-img {
			width: 100%;
			height: 100%;
			border-radius: 10rpx;
		}
	}
	.tui-book-name {
		flex: 1;
		.title {font-size: 32rpx;}
	}
	.flex-num {
		flex: 1;
		text-align: left;
		font-size: 34rpx;
	}
	.ui-dashed {
		border-bottom: 1px dashed #eee;
	}
	.ipt {flex: 1;}
	.uni-easyinput {
		text-align: right;
		font-size: 32rpx;
	}
	.num-bot {
		font-size: 40rpx;
		text-align: right;
		padding-top: 10rpx;
	}
	.l_item {
		padding: 16rpx 0;
		display: flex;
		align-items: center;
		font-size: 32rpx;
		border-bottom: 2rpx solid #eee;
		&:last-child {
			border-bottom: 0;
		}
	}
</style>
